package com.jrx.anytxn.atom.service.impl;

import com.jrx.anytxn.atom.bean.CustBatchSaveBean;
import com.jrx.anytxn.atom.service.BaseBatchAccoutHandle;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.customer.entity.CmCustomerFirstLevel;
import com.jrx.anytxn.investor.bean.InvestorDealDelqBean;
import com.jrx.anytxn.investor.bean.InvestorDelqSaveBean;
import com.jrx.anytxn.investor.entity.*;
import com.jrx.anytxn.investor.service.IInvestorDealDelqService;
import com.jrx.anytxn.param.entity.PrDelqTable;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.product.IDelqTableService;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.bean.DelqSaveBean;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: anytxn-cf-parent
 * @description: 联合贷批量-延滞处理
 * @author: xiaoyu.jing
 * @date: 2020-09-01 09:35
 **/
@Order(120)
@Service
public class InvestorDelqHandle extends BaseBatchAccoutHandle<InvestorDelqSaveBean> {

    Logger logger = LoggerFactory.getLogger(InvestorDelqHandle.class);

    @Autowired
    private IOrganizationTableService organizationTableService;

    @Autowired
    private IInvestorDealDelqService delqService;

    @Autowired
    private IDelqTableService delqTableService;

    /**
     * 延滞业务逻辑处理
     * @return
     * @throws TxnException
     */
    @Override
    public List<InvestorDelqSaveBean> handBatchAccout() throws TxnException {
        CustBatchSaveBean custBatchSaveBean = CustBatchHelper.getCustBatchLocal();
        List<AmRepaymentPlanInvestorInfo> dealPlanList = custBatchSaveBean.getDealInvestorPlanList();
        if (CollectionUtils.isEmpty(dealPlanList)) {
            return null;
        }

        List<InvestorDelqSaveBean> delqSaveBeanList = new ArrayList<>();
        CmCustomerFirstLevel firstLevel = custBatchSaveBean.getDealCust();
        String tenantId = firstLevel.getTenantId();
        PrOrganizationTable org = organizationTableService.findByOrId(TransBizConstant.DEFAULT_ORG_ID,tenantId);
        Date today = org.getToday();
        Date lastProcessDay = org.getLastProcessingDate();
        List<AmRepaymentPlanInvestorInfo> onDuePlanList = dealPlanList.stream()
                .filter(plan -> TransBizConstant.LOAN_PLAN_STATUS_1.equals(plan.getPlanStatus()))
                .filter(plan -> today.compareTo(plan.getPaymentDueDate())>=0)
                .filter(plan -> lastProcessDay.compareTo(plan.getPaymentDueDate())<=0)
                .collect(Collectors.toList());
        this.dealDelq(onDuePlanList,delqSaveBeanList,today);

        List<AmRepaymentPlanInvestorInfo> overDuePlanList = dealPlanList.stream()
                .filter(plan -> TransBizConstant.LOAN_PLAN_STATUS_2.equals(plan.getPlanStatus()))
                .collect(Collectors.toList());
        this.dealDelq(overDuePlanList,delqSaveBeanList,today);
        return delqSaveBeanList;
    }

    /**
     * 根据还款计划处理延滞
     * @param delqPlanList
     * @param delqSaveBeanList
     * @param today
     * @throws TxnBizException
     */
    private void dealDelq(List<AmRepaymentPlanInvestorInfo> delqPlanList,List<InvestorDelqSaveBean> delqSaveBeanList,Date today) throws TxnException {
        if(CollectionUtils.isEmpty(delqPlanList)){
            return;
        }

        CustBatchSaveBean custBatchSaveBean = CustBatchHelper.getCustBatchLocal();
        List<AmLoanMainInvestorInfo> dealLoanMainList = custBatchSaveBean.getDealInvestorLoanMainList();
        List<AmLoanAccountInvestorInfo> dealLoanAcctList = custBatchSaveBean.getDealInvestorLoanAccountList();
        List<AmAccountMainInvestorInfo> dealAcctList = custBatchSaveBean.getDealInvestorAcctList();
        List<AmDelinquencyInvestorInfo> dealDelqAcctList = custBatchSaveBean.getDealInvestorDelqAcctList();
        for(AmRepaymentPlanInvestorInfo delqPlan : delqPlanList){
            String investorloanId = delqPlan.getInvestorLoanId();
            int billingTenor = delqPlan.getBillingTenor();

            AmLoanMainInvestorInfo loanMainInfo = dealLoanMainList.stream().filter(loanMain -> investorloanId.equals(loanMain.getInvestorLoanId())).findFirst().get();
            AmLoanAccountInvestorInfo loanAccountInfo = dealLoanAcctList.stream().filter(loanAcct -> investorloanId.equals(loanAcct.getInvestorLoanId())).findFirst().get();

            //判断订单是否是核销订单
            if(TransBizConstant.YES_FLAG.equals(loanAccountInfo.getChargeoffFlag())){
                //获取延滞参数，根据延滞参数 核销后是否延滞处理标志 判断是否做延滞处理
                PrDelqTable prDelqTable = delqTableService.findByDelqId(loanMainInfo.getTenantId(),loanMainInfo.getDelqTableId());
                if(TransBizConstant.NO_FLAG.equals(prDelqTable.getChargeoffDelqFlag())){
                    continue;
                }
            }

            List<AmAccountMainInvestorInfo> acctList = dealAcctList.stream()
                    .filter(acct -> investorloanId.equals(acct.getInvestorLoanId()))
                    .filter(acct -> billingTenor == acct.getBillingTenor())
                    .filter(acct -> Arrays.asList(TransBizConstant.ACCOUNT_TYPE_04, TransBizConstant.ACCOUNT_TYPE_03
                            , TransBizConstant.ACCOUNT_TYPE_06).contains(acct.getAccountType()))
                    .filter(acct -> TransBizConstant.ACCOUNT_STATUS_1.equals(acct.getAccountStatus()))
                    .collect(Collectors.toList());
            AmDelinquencyInvestorInfo delqAcct = dealDelqAcctList.stream()
                    .filter(acct -> investorloanId.equals(acct.getInvestorLoanId()))
                    .filter(acct -> billingTenor == acct.getBillingTenor())
                    .findFirst().orElse(null);

            InvestorDealDelqBean bean = new InvestorDealDelqBean();
            bean.setBusinessDate(today);
            bean.setRepaymentPlanInfo(delqPlan);
            bean.setLoanMain(loanMainInfo);
            bean.setLoanAcct(loanAccountInfo);
            bean.setAcctList(acctList);
            bean.setDelqAcct(delqAcct);
            InvestorDelqSaveBean delqSaveBean = delqService.dealDelq(bean);
            delqSaveBeanList.add(delqSaveBean);
        }
    }
}
